package com.nineclock.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.entity.Result;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.document.dto.*;
import com.nineclock.document.enums.DocumentPermissionEnum;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFileHistory;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocFileService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class DocFileServiceImpl implements DocFileService {

    @Autowired
    private DocFolderMapper folderMapper;

    @Autowired
    private DocFileMapper fileMapper;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    @Autowired
    private DocCollaborationsMapper collaborationsMapper;

    @Autowired
    private DocFileHistoryMapper fileHistoryMapper;


    @Override
    public DocumentDto queryFolderAndFile(Long parentFoldId) {

        // 查询符合条件的文件夹列表
        List<DocFolderDto> folders = queryFolders(parentFoldId);

        // 查询符合条件的文件列表
        List<DocFileDto> files = queryFiles(parentFoldId);

        // 封装数据
        DocumentDto documentDto = new DocumentDto();
        documentDto.setFiles(files);
        documentDto.setFolders(folders);

        return documentDto;
    }


    /**
     * 查询符合条件的文件列表
     *
     * @param parentFoldId
     * @return
     */
    private List<DocFileDto> queryFiles(Long parentFoldId) {

        List<DocFile> fileList = new ArrayList<>();

        // 1.当前目录下，公共读/公共读写 的文件
        LambdaQueryWrapper<DocFile> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper1.eq(DocFile::getFolderId, parentFoldId);
        wrapper1.eq(DocFile::getStatus, 1);
        wrapper1.in(DocFile::getPermission, DocumentPermissionEnum.ALL_READ.getPermission(),
                DocumentPermissionEnum.ALL_READ_WRITE.getPermission());

        List<DocFile> fileList1 = fileMapper.selectList(wrapper1);
        if (!CollectionUtils.isEmpty(fileList1)) {
            fileList.addAll(fileList1);
        }

        // B.当前目录下，当前用户私有的文件
        LambdaQueryWrapper<DocFile> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper2.eq(DocFile::getFolderId, parentFoldId);
        wrapper2.eq(DocFile::getStatus, 1);
        wrapper2.eq(DocFile::getPermission, DocumentPermissionEnum.PRIVATE_READ_WRITE.getPermission());
        // 创建人id等于当前登录用户的员工id
        wrapper2.eq(DocFile::getCreateUserId, CurrentUserHolder.get().getCompanyUserId());

        List<DocFile> fileList2 = fileMapper.selectList(wrapper2);
        if (!CollectionUtils.isEmpty(fileList2)) {
            fileList.addAll(fileList2);
        }


        // C.当前目录下，当前用户是协作者的文件
        List<DocFile> fileList3 = fileMapper.selectFileListByCollaboration(CurrentUserHolder.get().getCompanyId(),
                parentFoldId, CurrentUserHolder.get().getCompanyUserId());

        if (!CollectionUtils.isEmpty(fileList3)) {
            fileList.addAll(fileList3);
        }

        // 文件去重，例如某些文件既是公共读，当前用户又是协作者
        HashSet<DocFile> fileHashSet = new HashSet<>(fileList);

        // 数据转换
        Set<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(fileHashSet, DocFileDto.class);

        List<DocFileDto> docFileDtoList = docFileDtos.stream().map(docFileDto -> {

            // 调用系统微服务Feign接口根据更新人员工id，查询更新人员工信息
            SysCompanyUserDTO updateUserDTO = companyUserFeign.queryCompanyUserById(docFileDto.getUpdateUserId()).getData();
            if (updateUserDTO != null) {
                docFileDto.setUpdateUserName(updateUserDTO.getUserName());
            }

            // 调用系统微服务Feign接口根据创建人员工id，查询创建人员工信息
            SysCompanyUserDTO createUserDTO = companyUserFeign.queryCompanyUserById(docFileDto.getCreateUserId()).getData();
            if (createUserDTO != null) {
                docFileDto.setUserName(createUserDTO.getUserName());
            }

            return docFileDto;

        }).collect(Collectors.toList());

        return docFileDtoList;

    }

    /**
     * 查询符合条件的文件夹列表
     *
     * @return
     */
    private List<DocFolderDto> queryFolders(Long parentFoldId) {
        LambdaQueryWrapper<DocFolder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFolder::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(DocFolder::getParentId, parentFoldId);
        wrapper.eq(DocFolder::getStatus, 1);

        List<DocFolder> docFolders = folderMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(docFolders)) {
            return BeanHelper.copyWithCollection(docFolders, DocFolderDto.class);
        }
        return null;
    }

    @Override
    public DocFileDto getFileByFileId(Long id) {
        DocFile docFile = fileMapper.selectById(id);
        return BeanHelper.copyProperties(docFile, DocFileDto.class);
    }

    @Override
    public List<DocUserCollaborationDTO> queryUsers(Long id) {

        // 调用系统微服务查询当前企业员工列表
        List<SysCompanyUserDTO> companyUserDTOS = companyUserFeign.queryAllCompanyUser().getData();

        // 根据文件id查询文件
        DocFile docFile = fileMapper.selectById(id);

        // 根据文件id查询协作者id集合
        LambdaQueryWrapper<DocCollaborations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocCollaborations::getFileId, id);
        List<DocCollaborations> collaborationsList = collaborationsMapper.selectList(wrapper);

        // 获取协作者id集合
        List<Long> companyUserIdList = collaborationsList.stream().map(docCollaborations -> {
            return docCollaborations.getCollaborationId();
        }).collect(Collectors.toList());


        // 数据转换，将员工DTO转为DocUserCollaborationDTO
        List<DocUserCollaborationDTO> docUserCollaborationDTOS = companyUserDTOS.stream().map(sysCompanyUserDTO -> {

            DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
            docUserCollaborationDTO.setId(sysCompanyUserDTO.getId());
            docUserCollaborationDTO.setUsername(sysCompanyUserDTO.getUserName());
            docUserCollaborationDTO.setImgUrl(sysCompanyUserDTO.getImageUrl());
            docUserCollaborationDTO.setPhone(sysCompanyUserDTO.getMobile());

            if (docFile.getCreateUserId().equals(sysCompanyUserDTO.getId())) {
                docUserCollaborationDTO.setState(1); // 拥有者
            } else if (companyUserIdList.contains(sysCompanyUserDTO.getId())) {
                docUserCollaborationDTO.setState(2); // 协作者
            } else {
                docUserCollaborationDTO.setState(0);
            }

            return docUserCollaborationDTO;

        }).collect(Collectors.toList());

        return docUserCollaborationDTOS;
    }

    /**
     * 张思源
     * 分页查询文件列表
     *
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public PageResult<DocFileDto> pagingFile(Integer page, Integer pageSize, String keyword) {
        //查询分页所有文件
        LambdaQueryWrapper<DocFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        //不为空，加模糊查询条件
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like(DocFile::getName, keyword);
        }
        IPage<DocFile> iPage = new Page<>(page, pageSize);
        iPage = fileMapper.selectPage(iPage, wrapper);

        List<DocFile> docFiles = iPage.getRecords();

        List<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(docFiles, DocFileDto.class);

        if (CollectionUtils.isEmpty(docFiles) || CollectionUtils.isEmpty(docFileDtos)) {
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }

        //封装数据
        List<DocFileDto> documentList = docFileDtos.stream().map(docFileDto -> {
            //调用feign查询创建者信息
            SysCompanyUserDTO companyUserDTO = companyUserFeign.queryCompanyUserOne(
                    docFileDto.getCreateUserId(), CurrentUserHolder.get().getCompanyId()).getData();
            if (companyUserDTO == null) {
                throw new NcException(ResponseEnum.USER_NOT_JOIN_COMPANY);
            }
            docFileDto.setCreator(companyUserDTO);
            docFileDto.setUserName(companyUserDTO.getUserName());
            //查询文件协作者
            LambdaQueryWrapper<DocCollaborations> fileIdWrapper = new LambdaQueryWrapper<>();
            fileIdWrapper.eq(DocCollaborations::getFileId, docFileDto.getId());
            List<DocCollaborations> docCollaborations = collaborationsMapper.selectList(fileIdWrapper);
            //获取协作者Id集合
            List<Long> collaborationIds = docCollaborations.stream().map(
                    DocCollaborations::getCollaborationId).collect(Collectors.toList());
            List<SysCompanyUserDTO> companyUserDTOS = new ArrayList<>();

            if (collaborationIds.size()==0){
                //调用feign查询协作者信息
                docFileDto.setCollaborations(new ArrayList<SysCompanyUserDTO>());
            }else {
                companyUserDTOS = companyUserFeign.queryCompanyUserList(collaborationIds,CurrentUserHolder.get().getCompanyId()).getData();
            }


                docFileDto.setCollaborations(companyUserDTOS);
            return docFileDto;
        }).collect(Collectors.toList());
        return new PageResult<>(iPage.getTotal(), iPage.getPages(), documentList);
    }


    /**
     * 吴伟豪
     * 封禁/解封文件
     * @param fileId
     * @param status
     */
    @Override
    public void updateFileStatus(Long fileId, Short status) {

        //判断是否为空
        if (fileId == null || status == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        DocFile docFile = new DocFile();

        //封装数据
        docFile.setStatus(status);
        docFile.setUpdateUserId(CurrentUserHolder.get().getCompanyUserId());
        docFile.setUpdateTime(new Date());

        //根据文件id查询文件
        LambdaQueryWrapper<DocFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFile::getId, fileId);

        fileMapper.update(docFile, wrapper);
    }

    /**
     * 吴伟豪
     * 查询文件历史记录
     * @param fileId
     * @return
     */
    @Override
    public List<DocFileHistoryDto> queryFileHistoryRecord(Long fileId) {

        //判断是否为空
        if (fileId == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        List<DocFileHistory> docFileHistoryList = new ArrayList<>();

        //根据文件id查询文件并根据时间升序
        LambdaQueryWrapper<DocFileHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFileHistory::getFileId, fileId);
        wrapper.orderByAsc(DocFileHistory::getOperateTime);

        List<DocFileHistory> fileHistoryList = fileHistoryMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(fileHistoryList)) {
            docFileHistoryList.addAll(fileHistoryList);
        }

        //将docFileHistory转换成DocFileHistoryDto，并将员工名字添加到fileHistoryDto中
        List<DocFileHistoryDto> fileHistoryDtoList = docFileHistoryList.stream().map(docFileHistory -> {

            DocFileHistoryDto fileHistoryDto = BeanHelper.copyProperties(docFileHistory, DocFileHistoryDto.class);

            //根据操作人的id查询系统微服务的feign接口，得到员工名字
            SysCompanyUserDTO companyUserDTO = companyUserFeign.queryCompanyUserById(fileHistoryDto.getOperateUserId()).getData();
            if (companyUserDTO != null) {
                fileHistoryDto.setUserName(companyUserDTO.getUserName());
            }

            return fileHistoryDto;
        }).collect(Collectors.toList());

        return fileHistoryDtoList;
    }
}
